package com.oocl.processdData.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

import com.oocl.processdData.comparator.CustomerBirthComp;
import com.oocl.processdData.comparator.CustomerIdComp;
import com.oocl.processdData.pojo.Customer;
import com.oocl.processdData.service.CustomerService;
import com.oocl.processdData.util.FileUtil;
import com.oocl.processdData.util.PrinterUtil;
import com.oocl.processdData.view.View;

public class CustomerServiceImpl implements CustomerService{

	@Override
	public String customersXML(Set<Customer> custs) {
		StringBuilder builder = new StringBuilder("");
		
		for(Customer cust:custs){
			builder.append("<Customer id=\""+cust.getId()+"\">"+"\r\n");
			builder.append("\t<name>"+cust.getName()+"</name>" +"\r\n");
			builder.append("\t<birthday>"+cust.getBirthday()+"</birthday>"+"\r\n");
			builder.append("\t<sex> "+cust.getSex()+"</sex>"+"\r\n");
			builder.append("\t<email>"+cust.getEmail()+"</email>"+"\r\n");
			builder.append("<Customer>"+"\r\n");
		}
		
		return builder.toString();
	}

	@Override
	public ArrayList<Customer> parseToCustomers(ArrayList<String> records) {
		ArrayList<Customer> customers = new ArrayList<Customer>();
		for(int i=0; i<records.size(); i++){
			String str[] = records.get(i).replaceAll("\\s+", ",").split(",");
			if(str.length == 5){
				Customer cust = new Customer(Integer.parseInt(str[0]), str[1], str[2], str[3], str[4]);
				customers.add(cust);
			}
		}
		return customers;
	}

	@Override
	public Set<Customer> sort(Set<Customer> orgCusts, Comparator<Customer> cmpa) {
		Set<Customer> newSet = new TreeSet<Customer>(cmpa);
		for(Customer c:orgCusts){
			newSet.add(c);
		}
		return newSet;
	}

	@Override
	public String getInputMsg(InputStream in) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		return reader.readLine();
	}

	@Override
	public void processCmd(String cmdType, Set<Customer> checkedCusts, OutputStream out) throws IOException {
		if(cmdType.equals("command1")){
			Set<Customer> idOrderedCusts = this.sort(checkedCusts, new CustomerIdComp());
			PrinterUtil.println(customersXML(idOrderedCusts), out);
			PrinterUtil.println("\t\n", out);
		}else if(cmdType.equals("command2")){
			Set<Customer> birthOrderedCusts = sort(checkedCusts, new CustomerBirthComp());
			PrinterUtil.println(customersXML(birthOrderedCusts), out);
			PrinterUtil.println("\t\n", out);
		}else if(cmdType.equals("command3")){
			Set<Customer> idOrderedCusts = this.sort(checkedCusts, new CustomerIdComp());
			FileUtil.store(customersXML(idOrderedCusts));
			
		}else{
			
		}
	}
}

